// src/video/video.controller.ts
import {
  Controller,
  Get,
  Header,
  NotFoundException,
  Param,
  Req,
  Res,
} from '@nestjs/common';
import type { Request, Response } from 'express';
import { createReadStream, statSync } from 'fs';
import { join } from 'path';

@Controller('video')
export class VideoController {
  private readonly videoPath = join(process.cwd(), 'uploads', 'videos');

  @Get(':filename')
  @Header('Content-Type', 'video/mp4') // 可根据扩展名动态设置
  streamVideo(
    @Req() req: Request,
    @Res() res: Response,
    @Param('filename') filename: string
  ) {
    const filePath = join(this.videoPath, filename);

    try {
      const stat = statSync(filePath);
      const fileSize = stat.size;

      const range = req.headers.range;
      if (!range) {
        // 如果没有 Range 头，返回整个文件（但通常浏览器会发 Range）
        res.status(200).set({
          'Content-Length': fileSize,
          'Content-Type': 'video/mp4',
        });
        createReadStream(filePath).pipe(res);
        return;
      }

      // 解析 Range 头，例如 "bytes=0-1023"
      const parts = range.replace(/bytes=/, '').split('-');
      const start = parseInt(parts[0], 10);
      const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;

      if (start >= fileSize) {
        throw new NotFoundException('Requested range not satisfiable');
      }

      const chunksize = end - start + 1;
      const fileStream = createReadStream(filePath, { start, end });

      res.status(206).set({
        'Content-Range': `bytes ${start}-${end}/${fileSize}`,
        'Accept-Ranges': 'bytes',
        'Content-Length': chunksize,
        'Content-Type': 'video/mp4',
      });

      fileStream.pipe(res);
    } catch (error) {
      res.status(500).send('Internal Server Error' + error);
    }
  }
}
